﻿using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;

namespace Coldairarrow.Business.Base_Manage
{
    /// <summary>
    ///操作OL尾程物流单
    /// </summary>
    public class OL_LogisticsBusiness
    {
        public IDbAccessor Db { get; set; }
        /// <summary>
        /// 操作ol尾程物流单对象
        /// </summary>
        public LogisticsInfoInterfaceBusiness _LogisticsInfo { get; set; }

        public OL_LogisticsBusiness(IDbAccessor db)
        {
            this.Db = db;
            _LogisticsInfo = new LogisticsInfoInterfaceBusiness();
        }



        public async Task ExecuteCURD(WebHookDTO webHookDTO)
        {
            if (webHookDTO.data.track_info.IsNullOrEmpty()) return;
            _LogisticsInfo.Filters.Clear();
            _LogisticsInfo.Filters.Add(
              //13:>,14>=15:<,16<=
              new OL_FilterDTO() { ControlId = "676cd4ca9e0bc69bf1b7a71c", DataType = 2, SpliceType = 1, FilterType = 2, Value = webHookDTO.data.number });//根据物流单号查询
            var orders = await _LogisticsInfo.QueryAsync<LogisticsInfo>(_LogisticsInfo.queryOption, _LogisticsInfo.tableField, _LogisticsInfo.SqlDb);

            LogisticsInfo row = await DataChange(webHookDTO);
            //判断万联是否存在物流单
            if (orders.IsNullOrEmpty() || orders.Count == 0)//不存则在新增
            {
                await Insert(new List<LogisticsInfo>() { row });
            }
            else//存在则判断是否大于1条大于需要先删除一条再进行更新另外一条
            {

                if (orders.Count > 1)
                {
                    List<LogisticsInfo> DeleteList = new List<LogisticsInfo>();
                    for (int i = 0; i < orders.Count - 1; i++)
                    {
                        DeleteList.Add(orders[i]);
                    }
                    await Delete(DeleteList);
                }
                if (row.state != "查询不到")
                {
                    row.RowId = orders[orders.Count() - 1].RowId;
                    await Update(new List<LogisticsInfo>() { row });
                }
            }



        }





        private async Task Update(List<LogisticsInfo> items)
        {
            //List<LogisticsInfo> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<LogisticsInfo>(Keys, "RowId")).ToList();//获取交集(更新项)
            List<OL_RowDTO> updataData = _LogisticsInfo.ConvertOL_Row(items, _LogisticsInfo.tableField);//需要更新的数据集合
            await _LogisticsInfo.ExecuteNoQuery<OL_RowDTO>(updataData, _LogisticsInfo.upDateOption, _LogisticsInfo.SqlDb);//执行更新
        }

        private async Task Insert(List<LogisticsInfo> items)
        {
            //List<LogisticsInfo> insertItem = sourceData.Except(targetData, new ComparerFromKey<LogisticsInfo>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
            List<OL_RowDTO> insertData = _LogisticsInfo.ConvertOL_Row(items, _LogisticsInfo.tableField);//需要新增的数据集合
            await _LogisticsInfo.ExecuteNoQuery<OL_RowDTO>(insertData, _LogisticsInfo.insertOption, _LogisticsInfo.SqlDb);//执行插入行
        }

        private async Task Delete(List<LogisticsInfo> items)
        {
            //List<LogisticsInfo> deleteItem = targetData.Except(sourceData, new ComparerFromKey<LogisticsInfo>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)

            //List<LogisticsInfo> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
            ////将重复的项也一起加入删除的列表
            //deleteItem.AddRange(repeatItem);
            ////筛选出删除列表中重复的项
            //var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
            //deleteItem.AddRange(temp);

            List<OL_RowDTO> deleteData = _LogisticsInfo.ConvertOL_Row(items, _LogisticsInfo.tableField);//需要删除的数据集合
            await _LogisticsInfo.ExecuteNoQuery<OL_RowDTO>(deleteData, _LogisticsInfo.deleteOption, _LogisticsInfo.SqlDb);//执行删除行
        }




        /// <summary>
        /// 转换对象
        /// </summary>
        /// <param name="webHookDTO"></param>
        /// <returns></returns>
        private async Task<LogisticsInfo> DataChange(WebHookDTO webHookDTO)
        {

            LogisticsInfo row = new LogisticsInfo();
            await Task.Run(() =>
            {
                var data = webHookDTO.data;

                row.number = data.number;
                row.carrier = data.carrier.IsNullOrEmpty() ? "" : data.carrier.ToString();
                row.state = data.track_info.latest_status.status.IsNullOrEmpty() ? "" : data.track_info.latest_status.status;
                row.carrierName = data.track_info.tracking.providers[0].provider.name.IsNullOrEmpty() ? "" : data.track_info.tracking.providers[0].provider.name;
                row.tel = data.track_info.tracking.providers[0].provider.tel.IsNullOrEmpty() ? "" : data.track_info.tracking.providers[0].provider.tel;
                row.country = data.track_info.tracking.providers[0].provider.country.IsNullOrEmpty() ? "" : data.track_info.tracking.providers[0].provider.country;
                row.homepage = data.track_info.tracking.providers[0].provider.homepage.IsNullOrEmpty() ? "" : data.track_info.tracking.providers[0].provider.homepage;
                row.service_type = data.track_info.tracking.providers[0].service_type.IsNullOrEmpty() ? "" : data.track_info.tracking.providers[0].service_type;
                var nowTime = DateTime.Now;
                row.updTime = nowTime.ToString("yyyy-MM-dd HH:mm:ss");
                if (!data.track_info.tracking.providers[0].events.IsNullOrEmpty())
                {
                    var events = data.track_info.tracking.providers[0].events.OrderByDescending(x => (x.time_raw.date + " " + x.time_raw.time).ToDateTime()).ToList();
                    StringBuilder sb = new StringBuilder();
                    sb.Append($"<p>物流商:{row.carrierName}");
                    sb.Append($"({row.service_type})-");
                    sb.Append($"国家:{row.country}-");
                    sb.Append($"电话:{row.tel}</p>");
                    sb.Append("");
                    bool isFrist = false;
                    DateTime berTime = new DateTime();
                    StringBuilder sb1 = new StringBuilder();
                    events.ForEach(x =>
                    {
                        //物流信息
                        sb.Append($"<p>{x.time_raw.date + " " + x.time_raw.time}</p>");
                        sb.Append("");
                        sb.Append($"<p>{x.address.country},");
                        sb.Append($"{x.location},");
                        sb.Append($"{x.stage}:");
                        sb.Append($"{x.description}</p>");
                        sb.Append("");


                        //物流状态持续时间
                        //if (!isFrist && !x.stage.IsNullOrEmpty() && !x.time_raw.date.IsNullOrEmpty() && x.stage != "DeliveryFailure" && x.stage != "Delivered" && x.stage != "Exception")
                        if (!isFrist && !x.stage.IsNullOrEmpty() && !x.time_raw.date.IsNullOrEmpty() && x.stage != "DeliveryFailure" && x.stage != "Delivered" && x.stage != "Exception" && row.state != "成功签收" && row.state != "查询不到")
                        {
                            var hour = nowTime - (x.time_raw.date + " " + x.time_raw.time).ToDateTime();
                            row.stateHour = hour.TotalHours.ToString("F2");

                        }
                        else if (x.stage == "DeliveryFailure" || x.stage == "Delivered" || x.stage == "Exception" || row.state == "成功签收" || row.state == "查询不到")
                        {
                            row.stateHour = "0";
                            //isFrist = true;
                        }

                        //物流状态历史记录
                        if (!x.stage.IsNullOrEmpty() && !x.time_raw.date.IsNullOrEmpty() && x.stage != "DeliveryFailure" && x.stage != "Delivered" && x.stage != "Exception")
                        {
                            if (!isFrist)
                            {
                                berTime = DateTime.Now;
                                isFrist = true;
                            }
                            var thisTime = (x.time_raw.date + " " + x.time_raw.time).ToDateTime();
                            var hour = (berTime - thisTime).TotalHours;
                            // 物流状态记录
                            sb1.Append($"<p>状态:{x.stage}--开始时间:{thisTime.ToString()}--持续时间:{hour.ToString("F2")}小时</p>");

                            //记录本次的出发时间
                            berTime = thisTime;
                        }



                    });
                    row.eventInfo = sb.ToString();
                    row.stateLog = sb1.ToString();
                }
                else
                {
                    row.eventInfo = "";
                }

                row.days_after_order = data.track_info.time_metrics.days_after_order.IsNullOrEmpty() ? "" : data.track_info.time_metrics.days_after_order;
                row.weight_raw = data.track_info.misc_info.weight_raw.IsNullOrEmpty() ? "" : data.track_info.misc_info.weight_raw;
                row.weight_kg = data.track_info.misc_info.weight_kg.IsNullOrEmpty() ? "" : data.track_info.misc_info.weight_kg;
                row.pieces = data.track_info.misc_info.pieces.IsNullOrEmpty() ? "" : data.track_info.misc_info.pieces;
                row.dimensions = data.track_info.misc_info.dimensions.IsNullOrEmpty() ? "" : data.track_info.misc_info.dimensions;
                row.dimensions = data.track_info.misc_info.dimensions.IsNullOrEmpty() ? "" : data.track_info.misc_info.dimensions;
                row.customer_number = data.track_info.misc_info.customer_number.IsNullOrEmpty() ? "" : data.track_info.misc_info.customer_number;

                row.shipper_country = data.track_info.shipping_info.shipper_address.country.IsNullOrEmpty() ? "" : data.track_info.shipping_info.shipper_address.country;
                row.shipper_state = data.track_info.shipping_info.shipper_address.state.IsNullOrEmpty() ? "" : data.track_info.shipping_info.shipper_address.state;
                row.shipper_city = data.track_info.shipping_info.shipper_address.city.IsNullOrEmpty() ? "" : data.track_info.shipping_info.shipper_address.city;
                row.shipper_street = data.track_info.shipping_info.shipper_address.street.IsNullOrEmpty() ? "" : data.track_info.shipping_info.shipper_address.street;

                row.recipient_country = data.track_info.shipping_info.recipient_address.country.IsNullOrEmpty() ? "" : data.track_info.shipping_info.recipient_address.country;
                row.recipient_state = data.track_info.shipping_info.recipient_address.state.IsNullOrEmpty() ? "" : data.track_info.shipping_info.recipient_address.state;
                row.recipient_city = data.track_info.shipping_info.recipient_address.city.IsNullOrEmpty() ? "" : data.track_info.shipping_info.recipient_address.city;
                row.recipient_street = data.track_info.shipping_info.recipient_address.street.IsNullOrEmpty() ? "" : data.track_info.shipping_info.recipient_address.street;

            });
            return row;

        }

    }
}